package com.eu.mybatis.partition.convert;

import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.util.deparser.StatementDeParser;

import com.eu.mybatis.config.PartitionConfig;
import com.eu.mybatis.partition.strategy.PartitionStrategy;

public abstract class AbstractSqlConverter implements SqlConverter {
	
	/**
	 * 转换statement
	 */
	abstract protected Statement convertStatement(Statement paramStatement, Object paramObject, String paramString);
	
	public String convert(Statement statement, Object params, String mappedId) {
		//1、转换statement，主要设置分表名称
		convertStatement(statement, params, mappedId);
		//2、将sql解析出来
		StatementDeParser deParser = new StatementDeParser(new StringBuilder(64));
		statement.accept(deParser);
		return deParser.getBuffer().toString();
	}

	/**
	 * 获取分表的表名
	 */
	public String getTargetTableName(String table, Object params, String mappedId) {
		String key = table + (mappedId == null ? "" : "-" + mappedId);
		PartitionStrategy strategy = PartitionConfig.getStrategy(key);
		if (strategy == null) {
			strategy = PartitionConfig.getStrategy(table);
			if (strategy == null) {
				return table;
			}
		}
		return strategy.getTargetTableName(table, params, mappedId);
	}

}